package com.suyundeng.menu.config;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.suyundeng.entity.SMenu;
import com.suyundeng.menu.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.List;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private IMenuService menuService;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry =
                http.authorizeRequests();
        registry.antMatchers("/login.html","/error.html","/elementui/**","/axios/**","/vue/**","/qs/**").permitAll();
        //给每个权限的url进行权限验证
        List<SMenu> menus = menuService.list();
        menus.forEach(menu -> {
            if (StringUtils.isNotBlank(menu.getMenuUrl())){
                registry.antMatchers(menu.getMenuUrl()).hasAuthority(menu.getMenuName());
            }
        });

        //其它都要验证
        registry.anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login.html")
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/index.html")
                .and()
                .logout()
                .logoutUrl("/logout.html")
                .logoutSuccessUrl("/login.html")
                .and()
                .csrf().disable();

        //解决iframe不能跳转的问题，set 'X-Frame-Options' to 'deny'
        http.headers()
                .frameOptions()
                .sameOrigin()
                .httpStrictTransportSecurity()
                .disable();
    }
}
